package cn.chuengxu._04_affairs;

import cn.chuengxu._05_transactionListener.MyTranListener;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;

/**======================================================================================
* @Title:
* @Description: 事务发送消息生产者,需要在启动生产者之前指定发送事务
* @Author: Mr.Zhang
* @Version: 1.0
* @Date:  2022/7/25 12:21
* @Parameters:
* @Return
======================================================================================*/
public class Producer {


    public static void main(String[] args) throws Exception {
        // 1.创建生产者的对象,并指定组名
        TransactionMQProducer affairsProducer = new TransactionMQProducer("affairs_Producer_hello");

        // 2.连接Mq
        affairsProducer.setNamesrvAddr("127.0.0.1:9876");

        // 指定发送事务
        affairsProducer.setTransactionListener(new MyTranListener());

        // 3.启动生产者
        affairsProducer.start();

        // 4.创建所需要发送的消息,第一个是填写消息的主题,第二个是消息的下级路径.第三个是消息的内容
        Message message = new Message("affairs_Hello","hello","Java复杂难学,趁早转行".getBytes(StandardCharsets.UTF_8));

        // 5.发送异步消息消息
        affairsProducer.send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送消息成功");
                System.out.println(sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                throwable.printStackTrace();
                System.out.println("发送消息失败");
            }
        });


        // 6.关闭生产者,因为是异步,所以可能还没返回回来就关流了,所以就注释掉关流
        // asynProducer.shutdown();

    }

}
